<template>
  <view class="code-btn" @click="getCode">
    {{time ? time + 's':'发送'}}
  </view>
</template>
<script>
  let timer = null
  export default {
    name:"code-btn",
    props:{
      phone:{
        type:[Number, String],
        default:''
      },
    },
    data(){
      return {
        time:0
      };
    },
    methods:{
      getCode(){
        if(this.timer > 0) return
        //调用api接口，接收验证码
        this.$api.getCaptchat({
          phone:this.phone
        }).then(res => {
          //当成功获取验证码时
          this.time = 60
          this.$toast('验证码:'+res)
          //每秒 time--
          this.timer = setInterval(()=>{
            this.time--
            if(this.time<= 0){
              clearInterval(this.timer)
            }
          },1000)
        }).catch(err => {
          //若获取验证码失败
          this.$toast(err,'请稍后重试')
        })
      }
    },
  }
</script>
